package com.cqq.boot.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

public class SysHandlerInterceptor implements HandlerInterceptor{
	
	private static final Logger log = LoggerFactory.getLogger(SysHandlerInterceptor.class);   

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		log.info("---------------------开始进入请求地址拦截----------------------------");
		String path = request.getServletPath();
		log.info(path);
		if (!(handler instanceof HandlerMethod) || path.matches(Constant.DONT_BE_HANDLER_PATH))
            return true;
		//从header中获取sessionToken
		String sessionToken = request.getHeader(Constant.SESSION_TOKEN);
		String clientType = request.getParameter(Constant.URL_CLIENT_TYPE);
		
		//从request中获取sessionToken
        if (!StringUtils.isEmpty(clientType) && clientType.equals(Constant.URL_CLIENT_TYPE_PC))
        	sessionToken = request.getParameter(Constant.SESSION_TOKEN);
		
        //sessionToken不为空时
        if(!StringUtils.isEmpty(sessionToken)){
        	if(findUser(sessionToken,request))
        		return true;
        }
        
        // 浏览器用utf8来解析返回的数据
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        // 用UTF-8转码，而不是用默认的ISO8859
        response.setCharacterEncoding("UTF-8");
        
        JSONObject json = new JSONObject();
        json.put("message", ResultCode.SESSIONTOKEN_FAIL_MSG);
        json.put("type", ResultCode.FAIL_TYPE);
        json.put("code", ResultCode.SESSIONTOKEN_FAIL);
        response.getWriter().print(json.toJSONString());
		return false;
	}

	private boolean findUser(String sessionToken, HttpServletRequest request) {
		//获取用户的两种方式。
		//1、从redis中查询（当session服务化的时候）（推荐）
		//2、从数据库查询
		request.setAttribute("usersetting", "usersetting");
		return true;
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");   
	}

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
					throws Exception {
		log.info("---------------视图渲染之后的操作-------------------------0");
	}
	

}
